package com.freecloud.javabasics.classload;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * 破坏双亲委派类加载
 * @Author: maomao
 * @Date: 2021-01-30 10:32
 */
public class DestroyAppointClassLoader extends ClassLoader {

    private FreeClassLoader freeClassLoader = new FreeClassLoader();

    private File classPathFile;

    public DestroyAppointClassLoader(){
        String classPath = FreeClassLoader.class.getResource("").getPath();
        this.classPathFile = new File(classPath);
    }


    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        //return super.loadClass(name);
        System.out.println("重载loadClass，破坏双亲委派加载");
        return getClass(name);
    }

    private Class<?> getClass(String name){
        if(classPathFile == null) {
            return null;
        }
        File classFile = new File(classPathFile,name.replaceAll("\\.","/") + ".class");
        if(!classFile.exists()){
            return null;
        }
        String className = FreeClassLoader.class.getPackage().getName() + "." + name;

        Class<?> clazz = null;
        try(FileInputStream in = new FileInputStream(classFile);
            ByteArrayOutputStream out = new ByteArrayOutputStream()){

            byte [] buff = new byte[1024];
            int len;
            while ((len = in.read(buff)) != -1){
                out.write(buff,0,len);
            }
            clazz = defineClass(className,out.toByteArray(),0,out.size());
        }catch (Exception e){
            e.printStackTrace();
        }
        return clazz;
    }

    public static void main(String[] args) {
        DestroyAppointClassLoader freeClassLoader = new DestroyAppointClassLoader();
        try {
            Class<?> clazz = freeClassLoader.loadClass("FreeString");
            System.out.println("class loader :" + clazz.getClassLoader());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}
